package net.ikenway.springboot.demo.Utils;

import com.google.gson.Gson;
import net.ikenway.springboot.demo.Model.Dto.TencentValidateResponseDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author MasterKenway <zk@ikenway.net>
 * @Description
 * @date Created Date 12/25/2020
 */
@Component
public class TCaptchaVerifyUtil {

    @Value("${tencent.appId}")
    private String appId;

    @Value("${tencent.appSecretKey}")
    private String appSecretKey;

    private static final String VERIFY_URI = "https://ssl.captcha.qq.com/ticket/verify?";

    public TencentValidateResponseDto validate(String ticket, String rand, String userIp) {
        TencentValidateResponseDto tencentValidateResponseDto = null;
        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.set("Accept", "application/json");

            RequestEntity<Void> requestEntity = RequestEntity.method(HttpMethod.GET, VERIFY_URI +
                    "aid=" + appId + "&AppSecretKey=" + appSecretKey + "&Ticket=" + ticket +
                    "&Randstr=" + rand + "&UserIP=" + userIp)
                    .headers(httpHeaders).build();
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity =  restTemplate.exchange(requestEntity, String.class);

            tencentValidateResponseDto = (new Gson()).fromJson(responseEntity.getBody(), TencentValidateResponseDto.class);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return tencentValidateResponseDto;
    }
}
